-module(props).
-export([init/0, loop/1]).
-include("cell_records.hrl").

init() ->
  gauss:dist_var_new(0,1),
  register(props, spawn(props, loop, [#props{}])).

loop(Props) ->
  receive
    exit ->
      #props{things = Things} = Props,
      send_to_things(Things, stop),
      ok;
    pause ->
      #props{things = Things} = Props,
      send_to_things(Things, pause),
      loop(Props);
    play ->
      #props{things = Things} = Props,
      send_to_things(Things, play),
      loop(Props);
    stop ->
      #props{things = Things} = Props,
      send_to_things(Things, stop),
      loop(Props);
    print_all ->
      io:format("props:~n~p~n", [Props]),
      loop(Props);
    {dead, Pid, Id} ->
      connector ! {dead, Id},
      NewProps = Props,%#props{things = lists:delete(Props#props.things, Pid)},
      loop(NewProps);
    {the_thing, #worm{} = Worm} ->
      #props{id = Id, things = Things} = Props,
      Pid = worm:init1(Id, Worm#worm{id = Id}),
      loop(Props#props{id = Id + 1, things = [Pid | Things]});
    {the_thing, X, Y, SpawnW, MinW, W, Speed} ->
      #props{id = Id, things = Things} = Props,
      Worm = #worm{id = Id, position = {X,Y}, spawn_weight = SpawnW, min_weight = MinW, weight = W, speed = Speed},
      Pid = worm:init2(Id, Worm),
      loop(Props#props{id = Id + 1, things = [Pid | Things]});
    {set, Tag, Val} ->
      loop(set(Props, Tag, Val));
    {get, Tag, Pid} ->
      Pid ! ret(Props, Tag),
      loop(Props)
  end.

% set(Props, Tag, Val)
set(Props, size, {X, Y}) ->
  Props#props{x = X, y = Y};
set(Props, x, Val) ->
  Props#props{x = Val};
set(Props, y, Val) ->
  Props#props{y = Val};
set(Props, veg, Val) ->
  Props#props{veg = Val}.

ret(#props{x = X, y = Y}, size) -> {size, X, Y};
ret(#props{x = X}, x) -> {x, X};
ret(#props{y = Y}, y) -> {y, Y};
ret(#props{veg = Veg}, veg) -> {veg, Veg}.

send_to_things([Th | Things], Msg) ->
  Th ! Msg,
  send_to_things(Things, Msg);
send_to_things([], _Msg) ->
  ok.


